from sqlalchemy.sql.schema import Column
from sqlalchemy.sql.sqltypes import Integer, String, SmallInteger
from werkzeug.security import generate_password_hash, check_password_hash

from app.models.base import Base, db
from app.libs.error_code import NotFound, AuthFailed

class User(Base):
    id = Column(Integer, primary_key=True)
    email = Column(String(24), unique=True, nullable=False)
    nickname = Column(String(24), unique=True)
    auth = Column(SmallInteger, default=1)
    _password = Column('password', String(100))
    
    @property
    def password(self):
        return self._password
    
    #加密密码
    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)
        
    @staticmethod
    def register_by_email(nickname, account, secret):
        with db.auto_commit():
            user = User()
            user.nickname = nickname
            user.email = account
            user.password = secret
            #数据库的insert操作
            db.session.add(user)
            
    @staticmethod
    def verify(email, password):  #检查用户是否存在
        user = User.query.filter_by(email=email).first()
        if not user:                            #用户不存在
            raise NotFound(f'{email} user not found')
        if not user.check_password(password):   #密码不正确
            raise AuthFailed()
        return {'uid': user.id}
    
    def check_password(self, raw):
        if not self._password:  #密码为空
            return False
        #check_password_hash为模块提供的校验密码的方法
        return check_password_hash(self._password, raw)
    
    
    
    
            
            